package logic

import (
	"context"

	"paper-pro/app/paperfile/model"
	"paper-pro/app/paperfile/rpc/internal/svc"
	"paper-pro/app/paperfile/rpc/pb/paperfile"
	"paper-pro/pkg/xerr"

	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type ListMetasLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListMetasLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListMetasLogic {
	return &ListMetasLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListMetasLogic) ListMetas(in *paperfile.ListMetasReq) (*paperfile.ListMetasResp, error) {
	papers, err := l.svcCtx.PaperModel.List(l.ctx, in.UserId, in.ParseStatus)
	if err != nil {
		if err == model.ErrNotFound {
			return nil, xerr.NewErrMsg("未查询到论文数据")
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询论文数据失败，用户ID: %d, err: %v", in.UserId, err)
	}

	paperMetas := make([]*paperfile.PaperFileMeta, len(papers))
	for i, p := range papers {
		var pm paperfile.PaperFileMeta
		copier.Copy(&pm, p)
		pm.Id = p.ID.Hex()
		pm.CreateAt = p.CreateAt.Unix()
		pm.UpdateAt = p.UpdateAt.Unix()
		paperMetas[i] = &pm
	}

	return &paperfile.ListMetasResp{
		Metas: paperMetas,
	}, nil
}
